import { NextRequest } from "next/server";
// 暂时注释掉静态导入，使用动态导入来定位问题
// import { buildRagGraph } from "@/LangGraph/instance/ConditionalEdges";
// import { RagState } from "@/LangGraph/instance/state";

// 使用 nodejs runtime，因为 PGVectorStore 需要 Node.js 的原生模块支持
// export const runtime = "nodejs";

export async function POST(req: NextRequest) {
  try {
    console.log("📨 收到请求");
    // 解析请求体
    const body = await req.json().catch((e) => {
      console.error("❌ 解析请求体失败:", e);
      return {};
    });
    console.log("📝 请求体:", body);
    
    // 步骤1: 测试导入 ConditionalEdges 模块
    let buildRagGraphFunc;
    try {
      console.log("🔍 步骤1: 尝试导入 buildRagGraph...");
      const conditionalEdgesModule = await import("@/LangGraph/instance/ConditionalEdges");
      buildRagGraphFunc = conditionalEdgesModule.buildRagGraph;
      console.log("✅ 步骤1: 导入成功");
    } catch (importError: unknown) {
      const errorMessage = importError instanceof Error ? importError.message : String(importError);
      const errorStack = importError instanceof Error ? importError.stack : undefined;
      console.error("❌ 步骤1: 导入失败:", importError);
      return Response.json({ 
        ok: false, 
        message: `导入失败: ${errorMessage}`,
        stack: process.env.NODE_ENV === 'development' ? errorStack : undefined
      }, { status: 500 });
    }
    
    // 步骤2: 测试调用 buildRagGraph 函数
    try {
      console.log("🔨 步骤2: 开始构建图...");
      await buildRagGraphFunc();
      console.log("✅ 步骤2: 图构建成功");
      return Response.json({ ok: true, message: "图构建成功（未执行）", body });
    } catch (buildError: unknown) {
      const errorMessage = buildError instanceof Error ? buildError.message : String(buildError);
      const errorStack = buildError instanceof Error ? buildError.stack : undefined;
      console.error("❌ 步骤2: 构建图失败:", buildError);
      console.error("❌ 错误堆栈:", errorStack);
      return Response.json({ 
        ok: false, 
        message: `构建图失败: ${errorMessage}`,
        stack: process.env.NODE_ENV === 'development' ? errorStack : undefined
      }, { status: 500 });
    }

    // try {
    //   console.log("🚀 开始执行图...");
    //   const initialState: Partial<RagState> = {
    //     question: body.question || "什么是 LangGraph？",
    //     retriever: (body.retriever || "hybrid") as RagState["retriever"],
    //     hits: [], 
    //     retrievedDocs: [],
    //     fused: [], 
    //     logs: [],
    //   };
    //   console.log("📊 初始状态:", JSON.stringify(initialState, null, 2));
    //   out = await app.invoke(initialState as any);
    //   console.log("✅ 图执行成功");
    // } catch (invokeError: any) {
    //   console.error("❌ 执行图失败:", invokeError);
    //   console.error("❌ 错误堆栈:", invokeError?.stack);
    //   return Response.json({ 
    //     ok: false, 
    //     message: `执行图失败: ${invokeError?.message || String(invokeError)}`,
    //     stack: process.env.NODE_ENV === 'development' ? invokeError?.stack : undefined
    //   }, { status: 500 });
    // }

  } catch (e: unknown) {
    const errorMessage = e instanceof Error ? e.message : String(e);
    const errorStack = e instanceof Error ? e.stack : undefined;
    console.error("❌ API路由未知错误:", e);
    return Response.json({ 
      ok: false, 
      message: `服务器错误: ${errorMessage}`,
      stack: process.env.NODE_ENV === 'development' ? errorStack : undefined
    }, { status: 500 });
  }
}
